<template>
  <el-dialog
    title="修改密码"
    v-model="visible"
    width="400px"
    @close="reset">
    <el-form
      ref="formRef"
      :model="form"
      label-width="90px"
      :rules="rules">
      <el-form-item label="原密码" prop="oldPassword">
        <el-input v-model="form.oldPassword" show-password />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="form.newPassword" show-password />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible=false">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { updatePassword } from '@/api/auth'
import { useAuthStore } from '@/stores/auth'

const auth = useAuthStore()
const visible = ref(false)
const formRef = ref()
const form = reactive({ oldPassword:'', newPassword:'' })

const rules = {
  oldPassword: [{ required:true, message:'请输入原密码', trigger:'blur' }],
  newPassword: [{ required:true, message:'请输入新密码', trigger:'blur' }]
}

function reset(){
  form.oldPassword = ''
  form.newPassword  = ''
}

async function submit(){
  await formRef.value.validate()
  await updatePassword(form)
  ElMessage.success('密码已更新，请重新登录')
  auth.clear()
  location.reload()
}

defineExpose({ open: () => visible.value = true })
</script>